const util = require('util')

const axios = require('axios')
const consola = require('consola')

const CLOUD_FUNCTION_DOMAIN = 'https://lkqtjze7.fn.bytedance.net'
const CLOUD_FUNCTION_URL_MAP = {
  latest_one_data: `${CLOUD_FUNCTION_DOMAIN}/latest_one_data`,
  latest_one_data_rollback: `${CLOUD_FUNCTION_DOMAIN}/latest_one_data_rollback`,
  store_publishing_pkgs: `${CLOUD_FUNCTION_DOMAIN}/store_publishing_pkgs`,
  save_with_param: `${CLOUD_FUNCTION_DOMAIN}/save_with_param`,
  store_rollback_pkgs: `${CLOUD_FUNCTION_DOMAIN}/store_rollback_pkgs`,
}

function addInterceptorForAxios() {
  const printInfoWithConfig = (config) => {
    const data = `data: ${typeof config.data === 'object' ? util.inspect(config.data) : config.data}`
    return `url: ${config.url},method: ${config.method}, ${config.data && data}`
  }

  // Add a request interceptor
  axios.interceptors.request.use(
    function (config) {
      consola.info('requesting: ', printInfoWithConfig(config))
      return config
    },
    function (error) {
      consola.error(error)
      // Do something with request error
      return Promise.reject(error)
    },
  )

  // Add a response interceptor
  axios.interceptors.response.use(
    function (response) {
      // Any status code that lie within the range of 2xx cause this function to trigger
      // Do something with response data
      consola.success('request successfully: ', printInfoWithConfig(response.config))
      return response
    },
    function (error) {
      consola.error(error)
      // Any status codes that falls outside the range of 2xx cause this function to trigger
      // Do something with response error
      return Promise.reject(error)
    },
  )
}
addInterceptorForAxios()
module.exports = {
  CLOUD_FUNCTION_URL_MAP,
}
